﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions.Helpers;
using ZQNB.Common.Attributes;
using ZQNB.Common.Db;
using ZQNB.Common.NHExtensions;

namespace ZQNB.Web
{
    public static class NHibernateConfig
    {
        public static void SetupNHibernate(string dbName, bool rebulidSchema = false)
        {
            if (string.IsNullOrWhiteSpace(dbName))
            {
                throw new ArgumentException("必须指定DbName");
            }

            //动态发现需要注册的Assembly
            const string nhibernateMap = "NhibernateMap";
            NbAttributeHelper attHelper = new NbAttributeHelper();
            var mapperAssemblies = attHelper.FindAssemlbyWithNbAssembly(nhibernateMap).ToArray();

            string connStr = System.Configuration.ConfigurationManager.ConnectionStrings[dbName].ConnectionString;
            if (rebulidSchema)
            {
                SqlScriptHelper helper = new SqlScriptHelper();
                helper.ReCreateDbIfExist(connStr, dbName);
            }

            NbSessionFactoryForWeb.InitSessionFactory(MsSqlConfiguration.MsSql2005.ConnectionString(connStr),
                m =>
                {
                    //解决同类名映射问题
                    m.FluentMappings.Conventions.Setup(x => x.Add(AutoImport.Never()));
            
                    if (mapperAssemblies.Length > 0)
                    {
                        //需要在站架子统一注册的mapper
                        foreach (var mapperAssembly in mapperAssemblies)
                        {
                            m.FluentMappings.AddFromAssembly(mapperAssembly);
                        }
                    }
                }
                , rebulidSchema);
        }
    }
}